// 获取项目访问绝对路径
function getRealPath() {
	var curWwwPath = window.document.location.href;
	// 获取主机地址之后的目录，如： myproj/view/my.jsp
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	// 获取主机地址，如： http://localhost:8083
	var localhostPaht = curWwwPath.substring(0, pos);
	// 获取带"/"的项目名，如：/myproj
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	// 得到了 http://localhost:8083/myproj
	var realPath = localhostPaht + '/';
	return realPath;
}

// 判断是否为null
function panIsNull(variable1) {
	if (variable1 != null && variable1 !== undefined && variable1 != '') {
		return false;
	}
	return true;
}

// 右下角弹出信息 2秒关闭
function baseBottomMsgOpen(msg) {
	layer.open({
		offset : 'rb', // 右下角弹出
		shift : 2,
		time : 3000,
		icon : 1,
		skin : 'layui-layer-demo', // 样式类名
		content : msg,
		shadeClose : true, // 开启遮罩关闭
		shade : false,
		area : [ '260px', '140px' ],
		btn : []
	});
}

function eachBox(obj) {
	var array = '';
	$.each(obj, function(n, item) {
		array += $(item).val() + ',';
	});
	array = array.substring(0, array.length - 1);
	return array;
}
/**
 * 转化form中参数为java数据
 * 如果对象的,name使用xxx.xxx
 * @returns {{}}
 */
$.fn.serializeObject = function()
{
	var o = {};
	var arr={};
	var a = this.serializeArray();
	$.each(a, function() {
		if (this.name.indexOf('[]')>0) {
			var index=0;
			if(arr[this.name]){
				arr[this.name].push(this.value || '');
				index=arr[this.name].length-1;
			}else{
				arr[this.name]=[this.value];
			}
			o[parseNameToArr(this.name,index)] = this.value;
		} else {
			o[this.name] = this.value || '';
		}
	});
	function parseNameToArr(name,num){
		var s;
		var e;
		if(name.indexOf(".")>0){
			s=name.substring(0,name.indexOf("."));
			e=name.substring(name.indexOf("."),name.length);
		}else{
			s=name;
			e="";
		}
		s=s.replace("\[\]","["+num+"]");
		return s+e
	}
	return o;
};


/**
 * 弹窗
 * @param content
 * @param title
 */
function alertWindow(content, title, config) {
    return layer.open({
        type: 2,
        title:title,
        shadeClose: false,
        shade: [0.3, '#000'],
        maxmin: true, //开启最大化最小化按钮
        offset: '100px',
        area: ['750px', '500px'],
        content: content
    });
}

/**
 * 调接口
 * @param url
 * @param params
 * @param success
 */
function callapi(url, params, success) {
    $.ajax({
        type:'POST',
        url: getRealPath() + url,
        data:params,
        dataType:'json',
        success:success
    });
}


/**
 * 自动注册编辑的表格位，支持文本、图片、时间、商品
 * @param selector
 */
function auto_edit(selector) {
    $(selector).each(function (i) {
        var td = $(this);
        var value;
        if (selector === '.img') {
            value = td.find('img').attr('src');
        } else if (selector ==='.item'){
            value = td.html();
        } else {
            value = td.text().trim();
        }
        if (!value)
            value = '';
        initEdit(selector, value, td);
    });
}
function initEdit(selector, value, td) {
    var editor = new Editor(selector, value, td);
    td.html(editor.look);
    td.append(editor.edit);
    editor.edit.hide();
    td.on("dblclick", function () {
        editor.showEdit();
    });
    editor.edit.on(editor.event, function () {
        editor.look.show();
        $(this).hide();
        if (!editor.modify()) {
            return;
        }
        editor.complete();
        td.parent().find('.modify').removeAttr('disabled').removeClass('layui-btn-disabled');
    });
}

function Editor(selector, value, td) {
    switch (selector) {
        case '.edit':
            return new TextEditor(value, td);
        case '.img':
            return new ImgEditor(value, td);
        case '.time':
            return new TimeEditor(value, td);
        case '.item':
            return new ItemEditor(value, td);
    }
}

function TextEditor(value) {
    this.edit = $('<input class="text-input" value="' + value + '">');
    this.look = $("<p>" + value + "</p>");
    this.showEdit = function () {
        this.look.hide();
        this.edit.show().focus();
    };
    this.event = 'blur';
    this.complete = function () {
        var newValue = this.edit.val();
        this.look.text(newValue);
        var $td = this.look.parent();
        $td.parent().find('.modify').removeAttr('disabled').removeClass('layui-btn-disabled');
        var datafunc = $td.attr('data-func');
        if (datafunc) {
            eval(datafunc.replace('{value}', newValue).replace('{this}', '$td'));
        }
    };
    this.modify = function () {
        return this.edit.val() !== this.look.text();
    }
}

function TimeEditor(value, td) {
    this.edit = $('');
    this.look = value;
    this.showEdit = function () {
            td.parent().find('.modify').removeAttr('disabled').removeClass('layui-btn-disabled');
        var func = td.attr('data-func');
        if(func) {
            var f = func.replace("{this}", 'td');
        }
        layui.laydate({
            elem:td[0],
            format:'YYYY-MM-DD hh:mm:ss',
            istime:true,
            choose:function (value) {
                if (f) {
                    eval(f.replace("{value}", "'" + value + "'"));
                }
            }
        });
    };
    this.event = 'none';
    this.complete = function () {
        return '';
    };
    this.modify = function () {
        return false;
    }
}

function ImgEditor(value, td) {
    this.edit = $('<input type="file" name="file">');
    this.look = $("<img src='" + value + "' style='width: 50px; height: 50px;'>");
    this.showEdit = function () {
        var url;
        var look = this.look;
        var edit = this.edit;
        layui.use('upload', function(){
            layui.upload({
                url:'/goat/uploadpic.json',
                elem: edit[0],
                unwrap:true,
                success:function (data) {
                    if (data.result === "success") {
                        url = data.data;
                        look.attr('src', url);
                        td.parent().find('.modify').removeAttr('disabled').removeClass('layui-btn-disabled');
                    } else {
                        layui.layer.msg("接口失败");
                    }
                }
            });
        });
        this.edit.click();
        this.edit.hide();
    };
    this.event = 'change';
    this.complete = function () {
        return '';
    };
    this.modify = function () {
        return true;
    }
}

function ItemEditor(value, td) {
    this.edit = $('');
    this.look = function (value) {
        if (value.indexOf('<') !== -1) {
            return $(value);
        }
        return value;
    }(value);
    this.showEdit = function () {
        var $tr = td.parent();
        $tr.find('.item-choose').click();
    };
    this.event = 'none';
    this.complete = function () {
    };
    this.modify = function () {
        return true;
    }
}

function choose_item(btn, callback) {
    $(btn).parent().parent().attr('id', 'choos_item_id_tr');
    alertWindow('/goat/choose.htm', "选择商品", callback);
}